import { Component, OnInit, ElementRef, ViewChild, } from '@angular/core';
import { List } from 'linqts';
import { seriesData } from "../power-compare/compare-echarts/echarts.model";
import { WindPowerPairs, actualWPPairs } from "../../../entity/wind-power-pairs.model";
import { WindPowers } from "../../../entity/wind-powers.model";
import { WindPowerDrawService } from "../../../service/wind-power-draw.service";
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { Device } from "../../../entity/device.model";
import { NzMessageService } from 'ng-zorro-antd';
import { ApplicationService } from "../../../service/application.service";


@Component({
	selector: 'app-power-draw',
	templateUrl: './power-draw.component.html',
	styleUrls: ['./power-draw.component.css']
})
export class PowerDrawComponent implements OnInit {
	public farmCategory: FarmCategoryEnum = FarmCategoryEnum.winfarm;
	public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
	private originalActual: actualWPPairs[] = [];
	public actualWindPowerData: actualWPPairs[] = [];

	private originalWindPowerPoints: actualWPPairs[] = [];
	private windPowerPointsData: actualWPPairs[] = [];

	//型号设计曲线数据
	private originalModelWindPower: WindPowers[] = [];
	private modelWindPowerData: WindPowers[] = [];

	//实测功率点图表数据集合对象
	private windPowerPoints: SeriesDataDraw;

	//型号设计曲线
	private modelSeries: number[][] = [];

	//提示信息
	public windPowerHigh: boolean;
	public windPowerLow: boolean;
	public widthVarSpread: boolean;
	public widthVarUnnomal: boolean;

	/**
	 * 当前选中下标
	 * 
	 * @type {number}@memberof PowerCompareComponent
	 */
	active: number = 0;

	/**
	 * 时间间隔
	 * 
	 * @type {number}
	 * @memberof AlarmSearchComponent
	 */
	private timeInterval: number = 28;
	private timeIntervalYear: number = 366;

	/**
	* echart series(单个风机选择)
	* 
	* @type {any[]}@memberof TurbineTrendComponent
	*/
	powerSeries: seriesData[] = [];

	/**
	* 图例
	* 
	* @type {object}@memberof TurbineTrendComponent
	*/
	powerLegend: {};

	public maxPower: number;

	/**
	  * 当前风场风机
	  * 
	  * @type {Device}@memberof TurbineDetailComponent
	  */
	public currentDevice: Device;
	/**
	* 是否显示风机选择组件
	* 
	* @type {boolean}@memberof TurbineDetailComponent
	*/
	public showSelector: boolean = false;

	public turbineId: number;

	public endTime: Date = new Date();
	public end: Date = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate() + 1);
	public startTime: Date = new Date(this.endTime.getFullYear(), this.endTime.getMonth() - 1, this.endTime.getDate());

	//进度条
	public color = 'primary';
	public mode = 'indeterminate';

	public tabName: string = '风场信息';
	@ViewChild('tab')
	private tab: ElementRef;

	@ViewChild('ex')
	private ex: ElementRef;
	/**
	 *日期格式化
	 *
	 * @type {*}
	 * @memberof PowerDrawComponent
	 */
	en:any;
	constructor(
		public windPowerDrawService: WindPowerDrawService,
		private _message: NzMessageService,
		private application: ApplicationService,
	) { }

	ngOnInit() {
		this.en = {
			firstDayOfWeek: 0,
			dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
			dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
			monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
			today: '今天',
			clear: '清除'
		};
		// this.exportData();
	}

	/**
	  * 滑入风机系统tab时显示对应的风机系统
	  * 
	  * @type {}@memberof TurbineDetailComponent
	  */
	public onMouseEnter() {
		this.showSelector = true;
	}
	/**
	* 滑出风机系统tab时隐藏对应的风机系统
	* 
	* @type {}@memberof TurbineDetailComponent
	*/
	public onMouseLeave(ev) {
		if (!ev.toElement) return false;
		this.showSelector = false;
	}

	onSelectFarmRadio(ev: Device[]) {
		this.currentDevice = ev[0];
		this.turbineId = ev[0].deviceId;
		this.showSelector = false;

		this.onSearch();
	}

	public onClickHeader(n: number) {
		this.active = n;
		if (n == 0) {
			this.endTime = new Date();
			this.end = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate() + 1);
			this.startTime = new Date(this.endTime.getFullYear(), this.endTime.getMonth() - 1, this.endTime.getDate());
		} else if (n == 1) {
			this.endTime = new Date();
			this.end = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate() + 1);
			this.startTime = new Date(this.endTime.getFullYear(), this.endTime.getMonth() - 3, this.endTime.getDate());
		} else {
			this.endTime = new Date();
			this.end = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate() + 1);
			this.startTime = new Date(this.endTime.getFullYear() - 1, this.endTime.getMonth(), this.endTime.getDate());
		}

	}

	public onSearch() {
		this.initEchartsData();
	}

	private initEchartsData() {

		if (this.endTime > new Date()) {
			alert("结束时间不能大于当前时间");
			return;
		}
		if (this.startTime > this.endTime) {
			alert("起始时间不能大于结束时间");
			return;
		}

		let time = this.endTime.getTime() - this.startTime.getTime();// 毫秒数(5秒的延迟)
		let dayTime = time / 24 / 60 / 60 / 1000;  // 天

		if (dayTime < this.timeInterval || dayTime > this.timeIntervalYear) {
			alert("间隔时间必须大于28天且小于一年");
			return;
		}

		//实测风速功率集合
		this.originalActual = [];
		this.actualWindPowerData = [];
		//各损失点风速功率集合
		this.originalWindPowerPoints = [];
		this.windPowerPointsData = [];
		//型号设计数据
		this.originalModelWindPower = [];
		this.modelWindPowerData = [];
		this.modelSeries = [];
		//损失点数据对象
		this.windPowerPoints = {
			actualPower: [],
			widthVarPoint: [],
			stopPowerPoint: [],
			limitPowerPoint: [],
			unusualPowerPoint: [],
			psaaPowerPoint: [],
		}

		//根据风机id获取型号设计曲线
		this.windPowerDrawService.getDesignWindPowerByTurbineId(this.turbineId)
			.then(res => {
				if (res) {
					//型号设计曲线数据
					this.originalModelWindPower = [...res];
					this.modelWindPowerData = this.originalModelWindPower;

					//型号功率的最大值
					let powers = this.modelWindPowerData.map(o => o.power);
					this.maxPower = Math.max.apply(Math, powers) + 100;

					this.modelWindPowerData.forEach(o => {
						this.modelSeries.push([o.wind, o.power]);
					})
					this.setSeriesDate();
				}
			})
			.catch(error => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('获取型号设计曲线' + error, { nzDuration: 3000 });
				}

				//console.log("app-power-draw has error", error);
			})

		//根据风机id获取实测点数额
		this.windPowerDrawService.drawWindPowerDataByTurbineId(this.turbineId, this.startTime, this.end)
			.then(res => {
				if (res) {
					//各损失点风速功率集合
					this.originalWindPowerPoints = [...res.actualWPPairs];
					this.windPowerPointsData = this.originalWindPowerPoints;

					//实测功率曲线集合
					this.originalActual = [...res.actualPowerCurve]
					this.actualWindPowerData = this.originalActual

					if (res.performLossPercent > 10) {
						this.windPowerHigh = true;
					}
					if (res.performLossPercent < -10) {
						this.windPowerLow = true;
					}
					if (res.widthAverage >= 5) {
						this.widthVarSpread = true;
					}
					if (res.widthVar >= 1.4) {
						this.widthVarUnnomal = true;
					}

					//实测功率曲线
					let actualSeries: number[][] = [];
					this.actualWindPowerData.forEach(o => {
						actualSeries.push([o.windSpeed, o.griPower]);
					})

					//按照标识分组(markCount, 0,1,2,3,-1,-5)
					let list: List<actualWPPairs> = new List(this.windPowerPointsData);
					//按标识值分组
					let groups = list.GroupBy(grouper => grouper.flag, mapper => mapper);
					let flag = Object.getOwnPropertyNames(groups);

					let actualWindPowerArr: actualWPPairs[] = [];
					let seriesData: any[][] = [];

					flag.forEach(element => {
						actualWindPowerArr = Object.getOwnPropertyDescriptor(groups, element).value;
						let series: number[][] = [];
						actualWindPowerArr.forEach(o => {
							series.push([o.windSpeed, o.griPower]);
						})
						seriesData.push(series)
					})

					this.windPowerPoints = {
						actualPower: actualSeries,
						widthVarPoint: seriesData[0] != null ? seriesData[0] : [],
						stopPowerPoint: seriesData[5] != null ? seriesData[5] : [],
						limitPowerPoint: seriesData[4] != null ? seriesData[4] : [],
						unusualPowerPoint: seriesData[1] != null ? seriesData[1] : [].concat(seriesData[2] != null ? seriesData[2] : []),
						psaaPowerPoint: seriesData[3] != null ? seriesData[3] : [],
					}
					this.setSeriesDate();

				}
			})
			.catch(error => {
				this.setSeriesDate();
				if (this.application.appConfigData.isShowErr) {
					this._message.info('获取实测点数额' + error, { nzDuration: 3000 });
				}

				///console.log("app-power-draw has error", error);
			})

		this.setSeriesDate();
	}

	private setSeriesDate() {
		this.powerSeries = [
			{
				name: '设计曲线',
				type: 'line',
				z: 3,
				itemStyle : {
					normal: {
						lineStyle: {
							color: '#FF3300',
						}
					}
				},
				smooth: true,
				data: this.modelSeries //[[0, 100], [5, 200], [10, 100], [15, 600], [17, 300], [22, 400]],
			},
			{
				name: '实测功率曲线',
				type: 'line',
				z: 3,
				itemStyle : {
					normal: {
						lineStyle: {
							color: '#ffff00',
						}
					}
				},
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.actualPower : [] //[[0, 200], [5, 250], [9, 180], [12, 700], [19, 380], [24, 1500]],
			},
			{
				name: '功率主带点',
				type: 'scatter',
				symbolSize: 3,
				z: 1,
				itemStyle : {
					normal: {
						color: '#FFA500',
					}
				},
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.widthVarPoint : []//[[5, 200], [7, 250], [16, 180], [10, 700], [14, 380], [22, 1500]],
			},
			{
				name: '停机点',
				type: 'scatter',
				symbolSize: 3,
				itemStyle : {
					normal: {
						color: '#d81354',
					}
				},
				z: 1,
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.stopPowerPoint : []//[[8, 200], [9, 250], [6, 180], [10, 700], [16, 380], [21, 1500]],
			},
			{
				name: '限功率点',
				type: 'scatter',
				symbolSize: 3,
				itemStyle : {
					normal: {
						color: '#b513d8',
					}
				},
				z: 1,
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.limitPowerPoint : []//[[3, 200], [2, 250], [9, 180], [17, 700], [19, 380], [23, 1500]],
			},
			{
				name: '异常点',
				type: 'scatter',
				symbolSize: 3,
				z: 1,
				itemStyle : {
					normal: {
						color: '#FFFF00',
					}
				},
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.unusualPowerPoint : []//[[2, 200], [4, 250], [11, 180], [16, 700], [22, 380], [25, 1500]],
			},
			{
				name: '超功率点',
				type: 'scatter',
				symbolSize: 3,
				z: 1,
				itemStyle : {
					normal: {
						color: '#44fa33',
					}
				},
				smooth: true,
				data: this.windPowerPoints ? this.windPowerPoints.psaaPowerPoint : []//[[1, 500], [2, 250], [8, 180], [9, 700], [19, 380], [16, 1500]],
			},
		]

		this.powerLegend = {
			x: 'right',
			right: '5%',
			align: 'left',
			data: [{
				name: '设计曲线',
				textStyle: {
					color: '#FF3300',
				}
			}, {
				name: '实测功率曲线',
				textStyle: {
					color: '#ffff00',
				}
			}, '功率主带点', '停机点', '限功率点', '异常点', '超功率点'],
			orient: 'vertical',
			y: 50,
			textStyle: {
				color: ['#FF3300', '#ffff00', '#FFA500', '#d81354', '#b513d8', '#FFFF00', '#44fa33'],
				fontSize: 14
			}
		}
	}

	exportData() {
		// 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
		var html = "<html><head><meta charset='utf-8' /></head><body>" + document.getElementById("ex-tab").outerHTML + "</body></html>";
		// 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
		var blob = new Blob([html], { type: "application/vnd.ms-excel" });

		// var a = document.getElementsByTagName("a")[0];
		// 利用URL.createObjectURL()方法为a元素生成blob URL
		var href = URL.createObjectURL(blob);
		document.getElementById("ex").setAttribute("href", href);

		// // 设置文件名，目前只有Chrome和FireFox支持此属性
		document.getElementById("ex").setAttribute("download", "实际功率曲线.xls");
		// a.download = "实际功率曲线.xls";
		// a.click();
		// document.getElementById("ex").click();
	}
}

interface SeriesDataDraw {
	actualPower: any[];
	widthVarPoint: any[];
	stopPowerPoint: any[];
	limitPowerPoint: any[];
	unusualPowerPoint: any[];
	psaaPowerPoint: any[];
}



// WEBPACK FOOTER //
// ./src/app/module/performance/power-draw/power-draw.component.ts